package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<BrandEntity>();

        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }

        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }

    @Override
    public BrandEntity findOneById(Long brandId) {
        return baseMapper.selectById(brandId);
    }

    @Transactional
    @Override
    public void updateDetailsById(BrandEntity brand) {

        BrandEntity oldEntity = baseMapper.selectById(brand.getBrandId());

        baseMapper.updateById(brand);
        //修改category-brand关联表中的品牌名称冗余字段
        if (!oldEntity.getName().equals(brand.getName())) {
            categoryBrandRelationService.updateBrandNameByBrandId(brand.getBrandId(),brand.getName());
        }

    }

    @Override
    public void removeDetailByIds(List<Long> ids) {

        for (Long id : ids) {
            if (findOneById(id) != null) {
                baseMapper.deleteById(id);
                //级联删除 分类-品牌 关系中的数据
                categoryBrandRelationService.deleteByBrandId(id);
            }
        }


    }

}